#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <fstream>
#include <sstream>
#include "RwLock.hpp"

class Task
{
private:
    std::thread _reader;
    std::thread _writer;
    RwLock _rwlock;
public:
    Task()
    {
        _reader = std::thread([&]()
        {
            while(true)
            {
                _rwlock.rlock();
                std::cout<<"读者进入!\n";
                std::ifstream in("./test.log");
                if(in.is_open() == false)
                {
                    std::cerr<<"打开文件失败!"<<std::endl;
                    break;
                }
                std::string ss;
                ss.resize(4096);
                in.read(&(ss[0]),ss.size());
                printf("文件信息: %s\n",ss.c_str());
                _rwlock.unlock();
                sleep(1);
            }
        });
        _writer = std::thread([&]()
        {
            while(true)
            {
                _rwlock.wlock();
                std::cout<<"写者进入!\n";
                std::ofstream out("./test.log",std::ios::app);
                if(out.is_open() == false)
                {
                    std::cerr<<"打开文件失败!"<<std::endl;
                    break;
                }
                std::string msg = "hwllo word";
                out.write(msg.c_str(),msg.size());
                _rwlock.unlock();
                sleep(1);
            }
        });
    }
    ~Task()
    {
        _reader.join();
        _writer.join();
    }
};